<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>确认订单</p>
    </header>

    <div v-if="isLoading" class="loading">
      <p>正在加载订单信息...</p>
    </div>

    <div v-else>
      <!-- 订单信息部分 -->
      <div class="order-info">
        <h5>订单配送至：</h5>
        <div class="order-info-address" @click="toUserAddress">
          <p>{{ addressText }}</p>
          <i class="fa fa-angle-right"></i>
        </div>
        <p v-if="contactInfo">{{ contactInfo }}</p>
      </div>

      <h3>{{ businessName }}</h3>

      <!-- 订单明细部分 -->
      <ul class="order-detailed" v-if="cartItems.length > 0">
        <li v-for="item in cartItems" :key="item.cartId">
          <div class="order-detailed-left">
            <img :src="item.foodImg" @error="handleImageError" alt="商品图片" />
            <p>{{ item.foodName }} x {{ item.quantity }}</p>
          </div>
          <p>&#165;{{ item.totalPrice }}</p>
        </li>
      </ul>
      
      <div v-else class="no-items">
        <p>购物车为空</p>
      </div>
      
      <div class="order-deliveryfee">
        <p>配送费</p>
        <p>&#165;{{ deliveryPrice }}</p>
      </div>

      <!-- 合计部分 -->
      <div class="total">
        <div class="total-left">&#165;{{ finalTotal }}</div>
        <div class="total-right" @click="toPayment">去支付</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, computed, onMounted } from "vue";
import { cartApi, orderApi } from '@/api';
// 导入默认商品图片
import defaultFoodImg from '@/assets/sp01.png';
import api from '@/api';

const router = useRouter();
const route = useRoute();

// 从本地存储获取用户信息
const user = JSON.parse(localStorage.getItem('user-info'));
console.log('Orders页面用户数据:', user);
const deliveryaddress = user ? JSON.parse(localStorage.getItem(user.id)) : null;
console.log('Orders页面配送地址:', deliveryaddress);
const businessId = route.query.businessId;
console.log('Orders页面商家ID:', businessId);
const business = ref({});
const cartArr = ref([]);
const isLoading = ref(true);

// 安全的计算属性
const addressText = computed(() => {
  return deliveryaddress && deliveryaddress.address ? deliveryaddress.address : "请选择送货地址";
});

const contactInfo = computed(() => {
  if (!deliveryaddress || !deliveryaddress.contactName) return null;
  const sex = deliveryaddress.contactSex == 1 ? "先生" : "女士";
  return `${deliveryaddress.contactName}${sex} ${deliveryaddress.contactTel || ''}`;
});

const businessName = computed(() => {
  return business.value && business.value.businessName ? business.value.businessName : "商家信息加载中...";
});

const deliveryPrice = computed(() => {
  return business.value && business.value.deliveryPrice ? business.value.deliveryPrice : 0;
});

const cartItems = computed(() => {
  if (!cartArr.value || !Array.isArray(cartArr.value)) return [];
  return cartArr.value.map(item => ({
    cartId: item.id || Math.random(),
    foodName: item.food && item.food.foodName ? item.food.foodName : '商品',
    foodImg: item.food && item.food.foodImg ? item.food.foodImg : defaultFoodImg,
    quantity: item.quantity || 0,
    totalPrice: ((item.food && item.food.foodPrice ? item.food.foodPrice : 0) * (item.quantity || 0)).toFixed(2)
  }));
});

// 计算商品总价
const foodTotal = computed(() => {
  if (!cartItems.value || cartItems.value.length === 0) return 0;
  return cartItems.value.reduce((sum, item) => sum + parseFloat(item.totalPrice), 0).toFixed(2);
});

// 计算最终总价 (商品总价 + 配送费)
const finalTotal = computed(() => {
  return (parseFloat(foodTotal.value) + parseFloat(deliveryPrice.value)).toFixed(2);
});

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = defaultFoodImg;
};

// 跳转到地址选择页面
const toUserAddress = () => {
  router.push({
    path: "/userAddress",
    query: { businessId: businessId },
  });
};

// 返回上一页
const goBack = () => {
  // 直接跳转到商家信息页面
  router.push({
    path: '/businessInfo',
    query: { businessId: businessId }
  });
};

// 获取商家信息
const getBusinessInfo = async () => {
  try {
    const result = await api.get(`/api/businesses/${businessId}`);
    business.value = result;
    console.log('商家信息:', business.value);
  } catch (error) {
    console.error('获取商家信息失败:', error);
    alert("获取商家信息失败，请重试");
  }
};

// 获取购物车数据
const loadCartData = async () => {
  try {
    // 传递商家ID，只获取该商家的购物车数据
    const result = await cartApi.getCartList(businessId);
    cartArr.value = result;
    console.log('购物车数据:', cartArr.value);
  } catch (error) {
    console.error('获取购物车失败:', error);
    cartArr.value = [];
  }
};

// 创建订单并跳转到支付页面
const toPayment = async () => {
  if (!deliveryaddress) {
    alert("请选择送货地址");
    return;
  }

  if (!cartItems.value || cartItems.value.length === 0) {
    alert("购物车为空");
    return;
  }
  
  // 检查是否达到起送价
  if (business.value && parseFloat(foodTotal.value) < business.value.startPrice) {
    alert(`商品总价未达到起送价，还差¥${(business.value.startPrice - parseFloat(foodTotal.value)).toFixed(2)}`);
    return;
  }

  try {
    // 构建创建订单的数据
    const orderData = {
      business: {
        id: parseInt(businessId)
      },
      deliveryAddress: {
        id: deliveryaddress.id
      },
      totalPrice: parseFloat(finalTotal.value),
      items: cartArr.value.map(item => ({
        food: {
          id: item.food.id
        },
        quantity: item.quantity,
        price: item.food.foodPrice
      }))
    };

    // 调用创建订单的API
    const newOrder = await orderApi.createOrder(orderData);

    // 跳转到支付页面，并传递订单信息
    router.push({
      path: "/payment",
      query: { 
        orderId: newOrder.id,
        businessName: business.value.businessName, 
        totalPrice: finalTotal.value 
      }
    });
  } catch (error) {
    console.error('创建订单失败:', error);
    alert("创建订单失败: " + error.message);
  }
};

// 初始化
onMounted(async () => {
  isLoading.value = true;
  try {
    // 并行加载数据以提高效率
    await Promise.all([getBusinessInfo(), loadCartData()]);
  } catch (error) {
    console.error('初始化数据失败:', error);
  } finally {
    isLoading.value = false;
  }
});
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** 加载状态 ******************/
.loading {
  width: 100%;
  margin-top: 12vw;
  padding: 10vw;
  text-align: center;
  color: #666;
  font-size: 4vw;
}

/****************** 空购物车 ******************/
.no-items {
  width: 100%;
  padding: 8vw;
  text-align: center;
  color: #999;
  font-size: 4vw;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper header i {
  position: absolute;
  left: 3vw;
  font-size: 6vw;
  color: #fff;
  cursor: pointer;
}

/****************** 订单信息部分 ******************/
.wrapper .order-info {
  /*注意这里，不设置高，靠内容撑开。因为地址有可能折行*/
  width: 100%;
  margin-top: 12vw;
  background-color: #0097ef;
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;
}

.wrapper .order-info h5 {
  font-size: 3vw;
  font-weight: 300;
}

.wrapper .order-info .order-info-address {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;

  font-weight: 700;
  user-select: none;
  cursor: pointer;
  margin: 1vw 0;
}

.wrapper .order-info .order-info-address p {
  width: 90%;
  font-size: 5vw;
}

.wrapper .order-info .order-info-address i {
  font-size: 6vw;
}

.wrapper .order-info p {
  font-size: 3vw;
}

.wrapper h3 {
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #ddd;
}

/****************** 订单明细部分 ******************/
.wrapper .order-detailed {
  width: 100%;
}

.wrapper .order-detailed li {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left {
  display: flex;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left img {
  width: 10vw;
  height: 10vw;
}

.wrapper .order-detailed li .order-detailed-left p {
  font-size: 3.5vw;
  margin-left: 3vw;
}

.wrapper .order-detailed li p {
  font-size: 3.5vw;
}

.wrapper .order-deliveryfee {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
}

/****************** 订单合计部分 ******************/
.wrapper .total {
  width: 100%;
  height: 14vw;

  position: fixed;
  left: 0;
  bottom: 0;

  display: flex;
}

.wrapper .total .total-left {
  flex: 2;
  background-color: #505051;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .total .total-right {
  flex: 1;
  background-color: #38ca73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;

  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
